package com.hxkcloud.nurse.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.YjhApplication;
import com.hxkcloud.nurse.beans.FileUploadBean;
import com.hxkcloud.nurse.config.ApplicationConfig;
import com.hxkcloud.nurse.popup.DateTimeSelectPopWindow;
import com.hxkcloud.nurse.popup.PictureSelectPopupWindow;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.BrightnessUtils;
import com.hxkcloud.nurse.utils.ImageOptionUtils;
import com.hxkcloud.nurse.utils.ImageVideoUtils;
import com.hxkcloud.nurse.utils.StringUtil;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * ProjectName: YJHCuzhong
 * PackageName: com.yjhcloud.stroke.activitys
 * Description:检查报告录入/编辑界面
 * Create by Ray.
 * Date: 2016/10/9 13:52
 */
public class MyReportInputActivity extends BaseActivity implements View.OnClickListener, PictureSelectPopupWindow.FinishListener {

    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;

    private TextView timeTV;//检查时间
    private EditText inputDataET;//输入数据
    private ImageView picIV;//检查图片
    private Button saveBtn;//保存按钮

    private boolean dataInput = false;
    private boolean isPicExist = false;

    private DateTimeSelectPopWindow datetimeSelect;
    private PictureSelectPopupWindow picSelect;

    private static final int TAKE_PHOTO_PICTURE = 1;
    private static final int SELECT_PICTURE = 3;
//    private ArrayList<String> imageUris;

    private static final int DEL_PHOTO = 101;

    private String timeStr = "";
    private String dataStr = "";
    private String picPathStr = "";//上传地址
    private String valueId = "";

    private List<FileUploadBean> fileResultBean;

    private String reportId = "";
    private String reportName = "";

    //是否现在完善信息
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;//不保存
    private TextView tv_easynotice_func;//保存

    float max = 0;
    float min = 0;

    private boolean isEditing = false;

    private TextView dataInputTV;
    private String unit = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_reportinput);
//        imageUris = new ArrayList<>();
        if (getIntent().hasExtra("reportId")) {
            reportId = getIntent().getStringExtra("reportId");
        }
        if (getIntent().hasExtra("reportName")) {
            reportName = getIntent().getStringExtra("reportName");
        }
        if (getIntent().hasExtra("max")) {
            max = getIntent().getFloatExtra("max", 0);
        }
        if (getIntent().hasExtra("min")) {
            min = getIntent().getFloatExtra("min", 0);
        }
        if (getIntent().hasExtra("unit")) {
            unit = getIntent().getStringExtra("unit");
        }
        initView();
        initPopup();
        initData();
        initListener();
    }

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_UPDATEMYREPORT_SUCCESS:
                dismisssLoading();
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    finish();
                }

                break;
            case MessageCode.NETWORKCODE_UPDATEMYREPORT_FAILURE:
                dismisssLoading();
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }

                break;
            case MessageCode.NETWORKCODE_FILEUPLOAD_SUCCESS:
                if (msg.obj != null) {
                    fileResultBean = (List<FileUploadBean>) msg.obj;
                    picPathStr = fileResultBean.get(0).getFilePath();
//                    picPathStr = fileResultBean.get(0).getUrl();
                    YiJiaHuNetWorkUtils.updateMyReport(reportId, timeTV.getText().toString(), inputDataET.getText().toString(), picPathStr, valueId, handler);
                }
                break;
            case MessageCode.NETWORKCODE_FILEUPLOAD_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.fileuploadfail));
                }
                break;

        }

    }

    @Override
    protected void initView() {

        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        tv_title.setText(reportName);

        dataInputTV = (TextView) findViewById(R.id.reportinput_tv_dataunit);
        dataInputTV.setText(unit);

        timeTV = (TextView) findViewById(R.id.reportinput_tv_time);
        inputDataET = (EditText) findViewById(R.id.reportinput_et_imputdata);
        inputDataET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (StringUtil.isEmpty(s.toString())) {
                    dataInput = false;
                    if (!isPicExist) {
                        isEditing = false;
                    }
                    saveBtn.setBackgroundResource(R.drawable.bt_grey);
                    saveBtn.setEnabled(false);
                } else {
                    dataInput = true;
                    isEditing = true;
//                    if (isPicExist) {
                    saveBtn.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
                    saveBtn.setEnabled(true);
//                    }
                }
            }


            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        picIV = (ImageView) findViewById(R.id.reportinput_iv_pic);
        saveBtn = (Button) findViewById(R.id.reportinput_btn_save);

        picSelect = new PictureSelectPopupWindow(this, screenWidth,
                screenHeight, this);


        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String curDay = sdf.format(cal.getTime());
        timeTV.setText(curDay);

    }

    private void initPopup() {
        popup_easynotice = new PopupWindow(this);
        View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(MyReportInputActivity.this);
            }
        });

        tv_easynotice_title.setText(getResources().getString(R.string.myreportinput_text_title));
        tv_easynotice_cancel.setText(getResources().getString(R.string.myreportinput_text_cancel));
        tv_easynotice_func.setText(getResources().getString(R.string.myreportinput_text_save));
    }

    @Override
    protected void initListener() {

        timeTV.setOnClickListener(this);
        picIV.setOnClickListener(this);
        saveBtn.setOnClickListener(this);

    }

    @Override
    protected void initData() {
        cameraPath = new File(ApplicationConfig.PicAndVideoUrl);
        if (!cameraPath.exists()) {
            cameraPath.mkdirs();
        }
        if (getIntent().hasExtra("time")) {
            timeStr = getIntent().getStringExtra("time");
            timeTV.setText(timeStr);
        }
        if (getIntent().hasExtra("data")) {
            dataStr = getIntent().getStringExtra("data");
            inputDataET.setText(dataStr);
            dataInput = true;
        }
        if (getIntent().hasExtra("valueid")) {
            valueId = getIntent().getStringExtra("valueid");

        }

        if (getIntent().hasExtra("picPath")) {
            picPathStr = getIntent().getStringExtra("picPath");
//            imageUris.add(picPathStr);
            if (picPathStr == null || "".equals(picPathStr)) {
                picPathStr = "";
                isPicExist = false;
                picIV.setImageResource(R.mipmap.report_add);
            } else {
                //载入图片
                isPicExist = true;
                imageLoader.displayImage(picPathStr, picIV, ImageOptionUtils.getInstance().getSimplePicOptions());
            }

        }

//        if (dataInput && isPicExist) {
        if (dataInput) {
            saveBtn.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
            saveBtn.setEnabled(true);
        } else {
            saveBtn.setBackgroundResource(R.drawable.bt_grey);
            saveBtn.setEnabled(false);
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                if (isEditing) {
                    popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                    BrightnessUtils.lightOff(this);
                } else {
                    finish();
                }

                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                finish();
                break;
            case R.id.tv_easynotice_func:
                popup_easynotice.dismiss();
                break;
            case R.id.reportinput_tv_time:
                if (datetimeSelect == null) {
                    datetimeSelect = new DateTimeSelectPopWindow(this);
                    datetimeSelect.setTimeListener(new DateTimeSelectPopWindow.TimeListener() {
                        @Override
                        public void setTime(String time) {
                            String timeStr = "";
                            if (time.contains(".")) {
                                timeStr = time.replace(".", "-");
                            }
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            long dateSelect = 0;
                            try {
                                dateSelect = sdf.parse(timeStr).getTime();
                            } catch (ParseException e) {
                            }
                            long nowDate = Calendar.getInstance().getTime().getTime();
                            if (dateSelect > nowDate) {
                                toastMsg(R.string.reportinput_text_wrongtime);
                                return;
                            }

                            timeTV.setText(timeStr);
                        }
                    });
                }
                closeInputMethodManager();
                datetimeSelect.show(ll_title);

                break;
            case R.id.reportinput_iv_pic:
                closeInputMethodManager();
                if (isPicExist) {
                    //查看大图
                    Intent iPhotos = new Intent(mContext, DisplayImageActivity.class);
//                    iPhotos.putExtra("path", imageUris.get(0));picPathStr
                    if ("".equals(picPathStr)) {
                        iPhotos.putExtra("path", cameraFile.getAbsolutePath());
                    } else {
                        iPhotos.putExtra("path", picPathStr);
                    }
                    startActivityForResult(iPhotos, DEL_PHOTO);

                } else {
                    //选择图片
                    picSelect.setType(1);
                    picSelect.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                }

                break;
            case R.id.reportinput_btn_save:
                StringUtil.zhugeTrack(mContext, "我的检查报告中任意报告的录入页面的保存按钮", "我的检查报告中任意报告的录入页面的保存按钮点击数");

                double inputdata = Double.parseDouble(inputDataET.getText().toString().trim());
                if (inputdata >= min && inputdata <= max) {
                    //保存
                    if (!"".equals(picPathStr)) {
                        loading();
                        YiJiaHuNetWorkUtils.updateMyReport(reportId, timeTV.getText().toString(), inputDataET.getText().toString(), picPathStr, valueId, handler);
                    } else {
                        if (cameraFile == null) {
                            loading();
                            YiJiaHuNetWorkUtils.updateMyReport(reportId, timeTV.getText().toString(), inputDataET.getText().toString(), picPathStr, valueId, handler);
                        } else {
                            loading();
                            List<File> images = new ArrayList<>();
                            images.add(cameraFile);
                            YiJiaHuNetWorkUtils.FileUpload(images, YjhApplication.file_image, handler);
                        }

                    }
                } else {
                    toastMsg(getResources().getString(R.string.myreportinput_text_wrongdata));
                    return;
                }


                break;
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        if (isEditing) {
            popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
            BrightnessUtils.lightOff(this);
        } else {
            finish();
        }
    }

    // 上传文件的内容

    private File cameraPath;
    private File cameraFile;
    private String cameraFileName;

    @Override
    public void onFinished(int options, int type) {
        cameraPath = new File(ApplicationConfig.PicAndVideoUrl);
        if (!cameraPath.exists()) {
            cameraPath.mkdirs();
        }
        Intent mIntent;
        if (options == 1) {// 打开相机
            if (type == 1) {// 拍照
                mIntent = new Intent();
                mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                if (cameraFileName == null) cameraFileName = System.currentTimeMillis() + ".jpg";
                if (cameraFile == null) cameraFile = new File(cameraPath, cameraFileName);
                mIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(cameraFile));
                startActivityForResult(mIntent,
                        TAKE_PHOTO_PICTURE);
            }
        } else if (options == 2) {// 打开相册
            if (type == 1) {// 相册选择照片
                mIntent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                mIntent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(mIntent,
                        SELECT_PICTURE);
            }
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO_PICTURE:
                    if (cameraFile != null) {
                        ImageVideoUtils.compressPicture(cameraFile, cameraFile);
                        Bitmap mBitmap = BitmapFactory.decodeFile(cameraFile.getAbsolutePath());
                        picIV.setImageBitmap(mBitmap);
//                        imageUris.clear();
//                        imageUris.add(cameraFile.getAbsolutePath());
                        isPicExist = true;
                        isEditing = true;
                        if (dataInput) {
                            saveBtn.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
                            saveBtn.setEnabled(true);
                        } else {
                            saveBtn.setBackgroundResource(R.drawable.bt_grey);
                            saveBtn.setEnabled(false);
                        }
                    }
                    break;
                case SELECT_PICTURE:
                    if (data.getData() != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            String u = ImageVideoUtils.getImagePathForUri(uri, mContext);
                            cameraFile = new File(u);
                            ImageVideoUtils.compressPicture(cameraFile, cameraFile);
                            Bitmap mBitmap = BitmapFactory.decodeFile(cameraFile.getAbsolutePath());
                            picIV.setImageBitmap(mBitmap);
//                            imageUris.clear();
//                            imageUris.add(u);
                            isPicExist = true;
                            isEditing = true;
                            if (dataInput) {
                                saveBtn.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
                                saveBtn.setEnabled(true);
                            } else {
                                saveBtn.setBackgroundResource(R.drawable.bt_grey);
                                saveBtn.setEnabled(false);
                            }

                        }
                    }
                    break;
                case DEL_PHOTO:
                    picIV.setImageResource(R.mipmap.report_add);
//                    imageUris.clear();
                    picPathStr = "";
                    isPicExist = false;
                    cameraFile = null;
                    if (dataInput) {
                        isEditing = true;
                        saveBtn.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
                        saveBtn.setEnabled(true);
                    } else {
                        isEditing = false;
                        saveBtn.setBackgroundResource(R.drawable.bt_grey);
                        saveBtn.setEnabled(false);
                    }


                    break;

            }
        }
    }


}
